import trinity
import blue
import uthread

class TurretSet():
    __guid__ = 'turret.TurretSet'
    turretsEnabled = [False]

    def Initialize(self, graphicID, locator, repeatDelay = 0, overrideBeamGraphicID = None, count = 1):
        graphicID = graphicID.lower()
        self.graphicID = graphicID
        self.weaponType = graphicID[2]
        self.stopShooting = False
        self.shootLoop = None
        self.repeatDelay = repeatDelay
        turretPath = 'res:/TestCases/turrets/Pulse_Medium_T1.red'
        self.turretSets = []
        for i in range(count):
            self.turretSets.append(trinity.Load(turretPath))
            self.turretSets[i].locatorName = ('locator_turret_' + str((i + locator)))

        blue.resMan.Wait()
        for turretSet in self.turretSets:
            for j in range(turretSet.muzzleCount):
                effect = trinity.Load('res:/model/effect3/turret/msp531.red')
                effect.source = None
                effect.dest = None
                turretSet.firingEffects.append(effect)


        self.weaponType = graphicID[2]
        self.repeatDelay = repeatDelay
        return self.turretSets



    def GetTurretSet(self, index = 0):
        return self.turretSets[index]



    def GetTurretSets(self):
        return self.turretSets



    def Release(self):
        return 



    def SetTarget(self, shipID, targetID):
        self.targetID = targetID
        self.shipID = shipID
        targetBall = sm.GetService('michelle').GetBall(targetID)
        if (targetBall is not None):
            for turretSet in self.turretSets:
                turretSet.targetObject = targetBall.model




    def SetAmmoColor(self, ammoTypeID):
        return 



    def StartShooting(self, ammoGFXid = None):
        self.stopShooting = False
        if ((self.shootLoop is not None) and self.shootLoop.alive):
            return 
        if (self.repeatDelay > 0):
            self.shootLoop = uthread.new(self.ShootInLoop, self.repeatDelay)
        else:
            self.Shoot()



    def Shoot(self):
        for turretSet in self.turretSets:
            turretSet.EnterStateFiring()




    def Rest(self):
        for turretSet in self.turretSets:
            turretSet.EnterStateIdle()




    def StopShooting(self):
        self.stopShooting = True
        for turretSet in self.turretSets:
            turretSet.targetObject = None




    def ShootInLoop(self):
        while not self.stopShooting:
            self.Shoot()
            blue.pyos.synchro.Sleep(self.repeatDelay)




    def SetShaderParameter(self, materialFilename):
        overrideEffect = trinity.Load(materialFilename)
        if (overrideEffect is not None):
            for turretSet in self.turretSets:
                for param in turretSet.turretEffect.parameters:
                    for overrideParam in overrideEffect.parameters:
                        if (param.name == overrideParam.name):
                            overrideParam.CopyTo(param)






    def FitTurrets(shipID, model):
        playerShip = False
        turretsFitted = {}
        modules = []
        if (shipID == eve.session.shipid):
            playerShip = True
            ship = sm.StartService('godma').GetItem(shipID)
            modules = [ (module.itemID,
             module.typeID,
             module.flag) for module in ship.modules ]
            raceID = cfg.invtypes.Get(ship.typeID).raceID
        else:
            slimItem = sm.StartService('michelle').GetBallpark().GetInvItem(shipID)
            moduleItems = slimItem.modules
            modules = [ (module[0],
             module[1],
             0) for module in moduleItems ]
            raceID = cfg.invtypes.Get(slimItem.typeID).raceID
        del model.turretSets[:]
        slotCounter = 1
        for (moduleID, typeID, flag,) in modules:
            to = cfg.invtypes.Get(typeID)
            groupID = to.groupID
            graphicID = to.graphicID
            if playerShip:
                slot = ((flag - const.flagHiSlot0) + 1)
            else:
                slot = slotCounter
            turretSet = None
            if ((groupID == const.groupStripMiner) or ((typeID == 17912) or (typeID == 24305))):
                turretSet = TurretSet()
                if (graphicID == 2526):
                    turretSets = turretSet.Initialize('aim111', slot, 5000, overrideBeamGraphicID='aim211')
                else:
                    turretSets = turretSet.Initialize('aim111', slot, 5000)
                model.turretSets.append(turretSet[0])
                turretsFitted[moduleID] = turretSet
                slotCounter += 1
            elif (groupID == const.groupGasCloudHarvester):
                turretSet = TurretSet()
                turretSets = turretSet.Initialize('gasminersmall', slot)
                model.turretSets.append(turretSets[0])
                turretsFitted[moduleID] = turretSet
                slotCounter += 1
            elif ((groupID in [const.groupEnergyWeapon,
             const.groupProjectileWeapon,
             const.groupHybridWeapon,
             const.groupMiningLaser]) or (typeID == 18068)):
                turretSet = TurretSet()
                if ((groupID == const.groupMiningLaser) or (typeID == 18068)):
                    turretSets = turretSet.Initialize(to.GraphicFile(), slot, 2500)
                else:
                    turretSets = turretSet.Initialize(to.GraphicFile(), slot)
                model.turretSets.append(turretSets[0])
                turretsFitted[moduleID] = turretSet
                slotCounter += 1
            if (turretSet is not None):
                if (raceID is const.raceAmarr):
                    turretSet.SetShaderParameter('res:/dx9/model/turret/shader/amarr_preset01.red')
                elif (raceID is const.raceGallente):
                    turretSet.SetShaderParameter('res:/dx9/model/turret/shader/gallente_preset01.red')
                elif (raceID is const.raceCaldari):
                    turretSet.SetShaderParameter('res:/dx9/model/turret/shader/caldari_preset01.red')
                else:
                    if (raceID is const.raceMinmatar):
                        turretSet.SetShaderParameter('res:/dx9/model/turret/shader/minmatar_preset01.red')

        model.RebuildTurretPositions()
        return turretsFitted


    FitTurrets = staticmethod(FitTurrets)

    def ToggleWinter2010TurretsEnabled_ToBeRemoved(enabled = False):
        TurretSet.turretsEnabled[0] = enabled


    ToggleWinter2010TurretsEnabled_ToBeRemoved = staticmethod(ToggleWinter2010TurretsEnabled_ToBeRemoved)

    def Winter2010TurretsEnabled_ToBeRemoved():
        return TurretSet.turretsEnabled[0]


    Winter2010TurretsEnabled_ToBeRemoved = staticmethod(Winter2010TurretsEnabled_ToBeRemoved)

exports = {'turret.TurretSet': TurretSet}

